package web_view_mapper

import (
	"context"
	"gorm.io/gorm"
	"sync"
	"transport/web/web_view"
)

type OrderDetailReportMapper struct {
	DB   *gorm.DB
	Ctx  context.Context
	Lock *sync.RWMutex
}

func (mapper *OrderDetailReportMapper) Page(pageIndex, pageSize int, orderCode, billSn, customerName, routeName, priorityLevel, status, trusteeName, goodsName string) (items []*web_view.OrderDetailReport, count int64, err error) {
	mapper.Lock.RLock()
	defer mapper.Lock.RUnlock()
	var countTmp int64 = 0
	table := mapper.DB.WithContext(mapper.Ctx)
	if orderCode != "" {
		table = table.Where("order_code like ?", "%"+orderCode+"%")
	}
	if billSn != "" {
		table = table.Where("trans_sn like ?", "%"+billSn+"%")
	}
	if customerName != "" {
		table = table.Where("customer_name like ?", "%"+customerName+"%")
	}
	if routeName != "" {
		table = table.Where("route like ?", "%"+routeName+"%")
	}
	if priorityLevel != "" {
		table = table.Where("priority_level = ?", priorityLevel)
	}
	if status != "" {
		table = table.Where("order_status = ?", status)
	}
	if trusteeName != "" {
		table = table.Where("trustee_name like ?", "%"+trusteeName+"%")
	}
	if goodsName != "" {
		table = table.Where("product_name like ?", "%"+goodsName+"%")
	}
	if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&items).Offset(-1).Limit(-1).Count(&countTmp).Error; err != nil {
		return nil, 0, err
	}
	return items, countTmp, nil
}

func (mapper *OrderDetailReportMapper) List(orderCode, billSn, customerName, routeName, priorityLevel, status, trusteeName, goodsName string) (items []*web_view.OrderDetailReport, count int64, err error) {
	mapper.Lock.RLock()
	defer mapper.Lock.RUnlock()
	var countTmp int64 = 0
	table := mapper.DB.WithContext(mapper.Ctx)
	if orderCode != "" {
		table = table.Where("order_code like ?", "%"+orderCode+"%")
	}
	if billSn != "" {
		table = table.Where("trans_sn like ?", "%"+billSn+"%")
	}
	if customerName != "" {
		table = table.Where("customer_name like ?", "%"+customerName+"%")
	}
	if routeName != "" {
		table = table.Where("route like ?", "%"+routeName+"%")
	}
	if priorityLevel != "" {
		table = table.Where("priority_level = ?", priorityLevel)
	}
	if status != "" {
		table = table.Where("order_status = ?", status)
	}
	if trusteeName != "" {
		table = table.Where("trustee_name like ?", "%"+trusteeName+"%")
	}
	if goodsName != "" {
		table = table.Where("product_name like ?", "%"+goodsName+"%")
	}
	if err := table.Find(&items).Offset(-1).Limit(-1).Count(&countTmp).Error; err != nil {
		return nil, 0, err
	}
	return items, countTmp, nil
}
